<script setup lang="ts">
  import { editPatientAPI, getPatientInfoAPI, postPatientAddAPI } from '@/apis/patient'
import type { EditPatientParams, PostPatientAddParams } from '@/types/patient'
import { ref } from 'vue'
  // 准备表单数据
  const formData = ref<PostPatientAddParams>({
    name: '',// 患者姓名
    idCard:'',// 患者身份证号
    defaultFlag:0,//是否设置为默认患者
    gender: 1,// 患者性别 1 男 0 女
  })
  // 表单校验规则
  const formRules = ref<UniHelper.UniFormsRules>({
    name: {
      rules: [
        { required: true, errorMessage: '请填写患者姓名' },
        {
          pattern: /^[\u4e00-\u9fa5]{2,5}$/,
          errorMessage: '患者姓名为2-5位中文',
        },
      ],
    },
    idCard: {
      rules: [
        { required: true, errorMessage: '请输入身份证号' },
        {
          pattern:
            /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/,
          errorMessage: '身份证号格式不正确',
        },
      ],
    },
    gender: {
      rules: [
        { required: true, errorMessage: '请选择性别' },
        {
          validateFunction:(rule,value,data,callback)=>{
            const idCardGenderNumber = formData.value.idCard.charAt(16)
            if(Number(idCardGenderNumber)%2 !== value){
              callback('性别与身份证不匹配')
            }
            return true
          }
        }
      ],
    },
  })
  // 整体表单校验
  const formRef = ref<UniHelper.UniFormsInstance>()
  const onSubmit = async () => {
    await formRef.value?.validate?.()
    if(props.id){
      const { name,idCard,defaultFlag,id,gender } = formData.value
      await editPatientAPI({ name,idCard,defaultFlag,id,gender })
    }else{
      await postPatientAddAPI(formData.value)
    }
    // #ifdef H5
    window.history.back()
    // #endif
    // #ifdef MP-WEIXIN
    uni.navigateBack()
    // #endif
    // console.log(res);
    // 提示添加成功，并返回上一页
    
    uni.showToast({title: '保存成功',icon: 'success'})
  }
  // switch开关
  const onChangeDefaultFlag = (e:UniHelper.SwitchOnChangeEvent)=>{
    // console.log(e);
    formData.value.defaultFlag = e.detail.value ? 1 : 0
  }
  // 接收页面参数
  const props = defineProps<{id?:string}>()
  // console.log(props);
  uni.setNavigationBarTitle({title: props.id ? '编辑患者' : '添加患者'})
  const getPatientInfo = async ()=>{
    if(props.id){
      // 有id 就获取患者信息
      const res = await getPatientInfoAPI(props.id)
      // console.log(res);
      formData.value = res.data
    }
  }
  getPatientInfo()
</script>

<template>
  <scroll-view>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="formRef" :model="formData" :rules="formRules">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
          v-model="formData.name"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
          v-model="formData.idCard"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
          v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="defaultFlag">
          <view class="uni-switch">
            <switch 
            :checked="formData.defaultFlag === 1"
            @change="onChangeDefaultFlag"
            color="#20c6b2" 
            style="transform: scale(0.7)" />
          </view>
        </uni-forms-item>
        <button @tap="onSubmit" class="uni-button">保存</button>
        {{ formData }}
      </uni-forms>
    </view>
  </scroll-view>
</template>

<style lang="scss">
  @import './index.scss';
</style>